﻿using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace IconMake
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Bitmap srcBitmap = null;//用于保存原图
        System.Drawing.Size size;//用于保存目标图标的大小

        public MainWindow()
        {
            InitializeComponent();
        }

        private void cmbSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (cmbSize.SelectedIndex == 0)
                size = new System.Drawing.Size(16, 16);
            else if (cmbSize.SelectedIndex == 1)
                size = new System.Drawing.Size(32, 32);
            else if (cmbSize.SelectedIndex == 2)
                size = new System.Drawing.Size(64, 64);
        }
        private void btnOk_Click(object sender, RoutedEventArgs e)
        {
            // 创建文件对话框实例
            OpenFileDialog dlg = new OpenFileDialog();

            // 设置文件过滤器，限定选择图片文件
            dlg.Filter = "图片文件|*.jpg;*.jpeg;*.png;*.bmp|所有文件|*.*";
            dlg.FilterIndex = 1; // 默认选择图片过滤器

            // 使用更通用的初始目录，而不是硬编码的"F:\\"
            // 例如：设置为“我的图片”文件夹或当前用户桌面
            dlg.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

            // 启用路径和文件存在检查，避免选择无效文件
            dlg.CheckPathExists = true;
            dlg.CheckFileExists = true;
            dlg.ValidateNames = true;

            // 显示对话框并处理结果
            if (dlg.ShowDialog() == true)
            {
                try
                {
                    string selectedFilePath = dlg.FileName;
                    txtImage.Text = selectedFilePath;

                    // 使用更安全的BitmapImage加载方式，避免GDI+内存泄漏
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad; // 立即加载并释放文件流
                    bitmapImage.UriSource = new Uri(selectedFilePath);
                    bitmapImage.EndInit();
                    srcBitmap = new Bitmap(dlg.FileName);
                    imgJpeg.Source = bitmapImage;
                }
                catch (Exception ex)
                {
                    // 处理加载图片时可能出现的异常（如文件损坏、无权限等）
                    MessageBox.Show($"加载图片时出错：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                    // 可选：清空已显示的内容
                    txtImage.Text = string.Empty;
                    imgJpeg.Source = null;
                }
            }
        }

        private void btnMake_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (txtImage.Text != "" && cmbSize.Text != "")
                {
                    SaveFileDialog dlg = new SaveFileDialog();
                    dlg.Filter = "图标(*.ico)|*.ico";
                    dlg.CheckPathExists = true;
                    if (dlg.ShowDialog() == true)
                    {
                        FileStream fs = new FileStream(dlg.FileName, FileMode.Create);
                        System.Drawing.Icon icon = ConvertBitmap2Ico(srcBitmap);
                        //将Icon保存的指定的输出
                        icon.Save(fs);
                        fs.Close();
                    }
                }
            }
            catch (Exception err)
            {
                System.Windows.MessageBox.Show(err.ToString());
            }
        }

        /// <summary>
        /// 实现bitmap到ico的转换
        /// </summary>
        /// <param name="bitmap">原图</param>
        /// <returns>转换后的指定大小的图标</returns>
        private Icon ConvertBitmap2Ico(Bitmap bitmap)
        {
            Bitmap icoBitmap = new Bitmap(bitmap, size);
            //获得原位图的图标句柄
            var a = icoBitmap.GetHicon();
            //从图标的指定WINDOWS句柄创建Icon
            System.Drawing.Icon icon = System.Drawing.Icon.FromHandle(a);
            return icon;
        }
    }
}
